module.exports = {
	getTotalByMember: getTotalByMember,
	getOrderListByMember: getOrderListByMember,
	getOrderItems: getOrderItems,
	getOrderCountByMember: getOrderCountByMember,
	getOrderInfo: getOrderInfo,
	getOrderItemsByOrderIds: getOrderItemsByOrderIds,
	getOrderPayments: getOrderPayments
};
var db = require('../common/database/db');

function getTotalByMember(memberId, type, cb) {
	db.queryWithParam("SELECT COUNT(id) AS quantity,SUM(amountDue) AS total FROM orders WHERE memberId= ? AND orderType =?", [memberId, type], function (err, data) {
		if (err) return cb(err);
		if (data.length == 0) return cb(null, null);
		return cb(null, data[0])
	});
}
//
function getOrderListByMember(memberId, startTime, endTime, cb) {
	var sql = "SELECT orders.*, orderitem.inventoryId, orderitem.show_order AS show_order FROM orders LEFT JOIN orderitem  ON orderitem.orders_id=orders.id WHERE " +
		"orderitem.inventoryId != '0000000000000000000000000000000' and orders.memberId = ? and orders.orderType<>'macct-deposit' and orders.closeTime between ? and ?  " +
		"GROUP BY orders.id ORDER BY orders.closeTime DESC"


	db.queryWithParam(sql, [memberId, startTime, endTime], function (err, orders) {
		if (!err) {
			for (var i in orders) {
				txJson(orders[i])
				orders[i].inventorypic = "http://app.menpuji.com/api/stores/" + orders[i].storeid + "/inventories/" + orders[i].inventoryid + "/pic/bin"
			}
		}
		cb(err, orders);
	});
}
function txJson(order) {
	order.cashier = JSON.parse(order.cashier);
	order.creator = JSON.parse(order.creator);
	order.extended = JSON.parse(order.extended);
	order.member = JSON.parse(order.member);
	order.membertype = JSON.parse(order.membertype);
}

function getOrderItems(orderId, cb) {
	db.queryWithParam("SELECT orderitem.*,orders.storeId FROM orderitem  LEFT JOIN orders ON orders.id=orderitem.orders_id WHERE orderitem.orders_id=? ORDER BY orderitem.show_order ASC", [orderId], function (err, data) {
		if (!err) {
			for (var i in data) {
				data[i].inventorypic = "http://app.menpuji.com/api/stores/" + data[i].storeid + "/inventories/" + data[i].inventoryid + "/pic/bin"
			}
		}
		cb(err, data);
	});
}
function getOrderItemsByOrderIds(orderIds, cb) {
	if (orderIds.length == 0) {
		return cb(null, null);
	}
	db.queryWithParam("select * from orderitem where orders_id in (?)", [orderIds], cb);
}


function getOrderInfo(orderId, cb) {
	db.queryWithParamSingle("SELECT * FROM orders where id=?", [orderId], function (err, tx) {
		if (!err) {
			txJson(tx);
		}
		cb(err, tx)
	});
}
function getOrderCountByMember(memberId, startTime, endTime, cb) {
	db.queryWithParamSingle("SELECT count(id) as countTotal FROM orders WHERE memberId = ? and createTime between ? and ?  ORDER BY createTime DESC ", [memberId, startTime, endTime], cb);
}

function getOrderPayments(checkoutId, cb) {
	db.queryWithParam("SELECT op.* FROM orderpayments op INNER JOIN checkout_orderpayments co ON op.id=co.payments_id WHERE co.checkout_id=?", [checkoutId], cb);
}



